﻿using DoNet.Helper;
using DoNet.Platform.BaiDu;
using DoNet.Platform.BaiDu.Model;

namespace DoNet.OAuth2.Platform
{
    /// <summary>
    /// 百度授权登录
    /// https://openauth.baidu.com/doc/doc.html
    /// </summary>
    public class OAuthBaiDu : OAuthBase
    {
        /// <summary>
        /// 平台
        /// </summary>
        public override OAuthServer Platform
        {
            get
            {
                return OAuthServer.baidu;
            }
        }

        /// <summary>
        /// 获取Authorization Code 的URL
        /// </summary>
        /// <returns></returns>
        public override string GetAuthorizeURL()
        {
            return TokenApi.GetAuthorizeUrl(AppKey, CallbackUrl, "baidu");
        }

        /// <summary>
        /// 获取是否通过授权。
        /// </summary>
        public override bool Authorize()
        {
            if (!string.IsNullOrEmpty(code))
            {
                var result = AccessToken.GetAccessToken(AppKey, AppSecret, code, CallbackUrl);
                if (result != null)
                {
                    if (result.success)
                    {
                        var res = JsonHelper.DeserializeObject<dynamic>(result.data);
                        if (res != null)
                        {
                            token = res.access_token;
                            expiresTime = Convert.ToDateTime(res.expires_time);

                            //获取授权用户信息
                            var res_user = TokenApi.GetUserInfo(token);
                            if (res_user != null)
                            {
                                if (res_user.success)
                                {
                                    var userInfo = JsonHelper.DeserializeObject<UserInfo>(res_user.data);
                                    if (userInfo != null)
                                    {
                                        openID = userInfo.openid;
                                        nickName = userInfo.username;
                                        headUrl = string.Format("https://himg.bdimg.com/sys/portrait/item/{0}", userInfo.portrait);
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return false;
        }
    }
}
